<?php

namespace App\Api\Repositories\Search;

use App\Models\Search\Search as Model;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;
use function PHPUnit\Framework\callback;

class SearchRepositories
{
    protected $eloquentClass = Model::class;

    /**
     * 记录搜索条件
     *
     * @param int $uid
     * @param array $data
     * @return void
     */
    public function create_data($uid, $data)
    {
        return $this->eloquentClass::create([
            'uid' => $uid,
            'city' => $data['city'],
            'sex' => $data['sex'],
            'age' => $data['min_age'] . '~' . $data['max_age'],
            'height' => $data['height'],
            'face_score' => $data['face_score'],
            'college_tab' => $data['college_tab'],
            'family' => $data['family'],
            'income' => $data['income'],
            'constellation' => $data['constellation'],
            'carandhouse' => $data['carandhouse'],
            'keyword' => $data['keyword'],
            'status' => 1,
        ]);
    }

    /**
     * 将搜索结果id保存下来
     *
     * @param int $uid
     * @param array $ids
     * @return void
     */
    public function save_result_ids($uid, $ids)
    {
        Redis::del("sr:ids:{$uid}");
        foreach ($ids as $id) {
            Redis::rpush("sr:ids:{$uid}", $id);
        }
    }

    /**
     * 根据编号获取id
     *
     * @param int $uid
     * @param int $number
     * @return void
     */
    public function use_number_get_id($uid, $number)
    {
        return Redis::lindex("sr:ids:{$uid}", $number);
    }

    /**
     * 外部信息搜索
     *
     * @param int $uid
     * @param string $search
     * @return void
     */
    public function select_exterior_data($uid, $search)
    {
        // 整理数据
        $options_repositories = new \App\Api\Repositories\OptionRepositories();
        $province = $options_repositories->use_city_get_province($search['city']);
        $data_search = [];
        foreach ($search as $key => $valye) {
            switch ($key) {
                case "sex":
                    $data_search['sex'] = $valye == '男' ? "1" : "2";
                    break;
                case "keyword":
                    if ($search['keyword'][0] != "") {
                        $data_search['keywords'] = $search['keyword'];
                    }
                    break;
                case "college_tab":
                    if ($search['college_tab'] != "") {
                        $data_search['school_type'] = $search['college_tab'];
                    }
                    break;
                case "height":
                    if ($search['height_section'][0] != "100" && $search['height_section'][0] != "250") {
                        $data_search['height'] = ['gte' => $search['height_section'][0], 'lte' => $search['height_section'][1]];
                    }
                    break;
                case "carandhouse":
                    if ($search['carandhouse'] != "") {
                        $data_search['assets'] = $search['carandhouse'];
                    }
                    break;
                case "income":
                    if ($search['income'] != "") {
                        $data_search['annual_income'] = $search['income'];
                    }
                    break;
                case "min_age":
                    if ($search['max_age'] != 150 && $search['min_age'] != 1) {
                        $data_search['age'] = ['gte' => $search['age_section'][0], 'lte' => $search['age_section'][1]];
                    }
                    break;
                case "family":
                    if ($search['family'] != "") {
                        $data_search['family'] = $search['family'];
                    }
                    break;
                case 'city':
                    if ($search['city'] != "") {
                        if ($province != "海外") {
                            $data_search['location'] = ['country' => '中国', 'province' => $province, 'city' => $search['city'], 'district' => ''];
                        }
                    }
                    break;
            }
        }
//        $data_search['is_authentication'] = "1";
//        [
//            'sex' => $search['sex'] == '男' ? 1 : 2,
//            'keywords' => $search['keyword'],
//            'school_type' => $search['college_tab'],
//            'height' => ['gte' => $search['height_section'][0], 'lte' => $search['height_section'][1]],
//            'location' => ['country' => '', 'province' => $province, 'city' => $search['city'], 'district' => ''],
//            'is_authentication' => '1',
//            'assets' => $search['carandhouse'],
//            'constellation' => $search['constellation'],
//            'annual_income' => $search['income'],
//            'age' => [],
//            'family' => $search['family'],
//        ]
        $data = [
            'search_criteria' => $data_search,
            'uid' => $uid
        ];

        //$response = Http::post('http://120.53.247.244:5000/search_list', $data);

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://120.53.247.244:5000/search_list',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        // 处理结果数据
        $response = json_decode($response, true);
        if ($response == NULL || $response['code'] != 200) {
            throwBusinessException('数据获取失败');
        }

        $SEDR = new \App\Api\Repositories\Search\SearchExogenousDataRepositories();
        $res = [];
        foreach ($response['data'] as $v) {
            if (count($res) >= 5) {
                break;
            }
            $SEDR->update_data($v['info']['uid'], json_encode($v['info']));
            $res[] = $v['info'];
        }
        return $res;
    }
}
